package top.ezzz.common;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ContextUtil;

public class UserContext {

    public static String TOKEN = "token";

    public static Cache<String, UserBase> tokenUserMap = CacheUtil.newTimedCache(30 * 60 * 1000);

    public static String getUserName() {
        UserBase userBase = getUser();
        if (userBase == null) {
            return null;
        }
        return userBase.getUserName();
    }


    public static UserBase getUser() {
        String token = getToken();
        if ("admin".equals(token)) {
            UserBase userBase = new UserBase();
            userBase.setUserName("admin");
            userBase.setPassword("123456");
            userBase.setToken("admin");
            return userBase;
        }
        return tokenUserMap.get(token);
    }

    public static UserBase addUser(UserBase userBase) {
        String token = userBase.getToken();
        if (StrUtil.isBlank(token)) {
            token = IdUtil.simpleUUID();
            userBase.setToken(token);
        }
        tokenUserMap.put(userBase.getToken(), userBase);
        return userBase;
    }

    public static UserBase removeUser(String token) {
        UserBase userBase = tokenUserMap.get(token);
        tokenUserMap.remove(token);
        return userBase;
    }

    public static String getToken() {
        Context httpContext = ContextUtil.current();
        String token = httpContext.header(TOKEN);
        if (StrUtil.isBlank(token)) {
            token = httpContext.param(TOKEN);
        }
        if (StrUtil.isBlank(token)) {
            token = httpContext.cookie(TOKEN);
        }
        return token;
    }


}
